<?php
session_start();
// 数据库连接配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: ". $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $userId = $_SESSION["user_id"];
    $message = $_POST["message"];

    // 检查消息字数限制
    if (mb_strlen($message, 'UTF-8') > 5000) {
        echo "消息字数不能超过5000字";
        exit;
    }

    // 检查消息发送频率限制
    $sql = "SELECT COUNT(*) as count FROM chat_records 
            WHERE user_id = $userId AND send_time >= DATE_SUB(NOW(), INTERVAL 1 MINUTE)";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    if ($row['count'] >= 20) {
        echo "1分钟内只能发送20条消息";
        exit;
    }

    // 对消息进行转义处理，防止SQL注入
    $message = $conn->real_escape_string($message);

    // 插入消息到数据库
    $sql = "INSERT INTO chat_records (user_id, message) VALUES ($userId, '$message')";
    if ($conn->query($sql) === TRUE) {
        echo "消息发送成功";
    } else {
        echo "Error: ". $sql. "<br>". $conn->error;
    }
}

$conn->close();
?>
